package com.ykht.proj.admin.controller.b;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ykht.proj.admin.api.entity.SysUser;
import com.ykht.proj.admin.service.SysUserService;
import com.ykht.proj.admin.utils.AES;
import com.ykht.proj.common.core.constant.CacheConstants;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.dto.UserExtDto;
import com.ykht.proj.coupon.entity.CnPerson;
import com.ykht.proj.coupon.vo.BindMiniVo;
import com.ykht.proj.coupon.vo.BindSjVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("b/user")
public class BSysUserController {

	@Resource
	private  RedisTemplate redisTemplate;
	@Resource
	private SysUserService sysUserService;

	@ApiOperation(value = "b端小程序绑定手机号")
	@PostMapping("/bindMini")
	public R bindMini(@RequestBody BindMiniVo bindMiniVo) {

		log.info("->小程序绑定手机号");
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		System.out.println(SecurityUtils.getUserId());
		System.out.println(user);
		String sessionKey = null;
		try {
			sessionKey = String.valueOf(redisTemplate.opsForValue().get(CacheConstants.USER_SEEESINKEY_BY_OPENID + user.getMiniOpenid()));
			log.info("->openid:{}，得到缓存中的sessionKey：{}", user.getMiniOpenid(), sessionKey);

			String result = AES.wxDecrypt(bindMiniVo.getEncrypted(), sessionKey, bindMiniVo.getIv());
//			String  result = SecureUtil.aes(sessionKey.getBytes()).setIv(bindMiniVo.getIv().getBytes()).decryptStr(bindMiniVo.getEncrypted());
			log.info("->aes解密,result:{}", result);
			JSONObject jsonObject = JSONObject.parseObject(result);
			String phoneNumber = jsonObject.getString("phoneNumber");

			if (sysUserService.getOne(Wrappers.lambdaQuery(SysUser.class)
					.eq(SysUser::getPhone, phoneNumber)
					.eq(SysUser::getUserType,SecurityUtils.getUser().getUserType())
					.ne(SysUser::getUserId,SecurityUtils.getUserId())) != null) {
				return R.failed("此手机号已经绑定过");
			}

			redisTemplate.delete(CacheConstants.USER_SEEESINKEY_BY_OPENID + user.getMiniOpenid());
			user.setPhone(phoneNumber);
			user.setLoginFlag(0);//登录正常
			user.setUpdateTime(LocalDateTime.now());
			sysUserService.updateById(user);
			return R.ok(phoneNumber);
		} catch (Exception e) {
			e.printStackTrace();
			redisTemplate.opsForValue().set(CacheConstants.USER_SEEESINKEY_BY_OPENID + user.getMiniOpenid(), sessionKey);
			return R.failed();
		}
	}

	/**
	 * 退出，小程序需要重新绑定手机号
	 * @return
	 */
	@ApiOperation(value = "b端小程序退出登录")
	@PostMapping("/logout")
	public R bindMini() {
		log.info("->用户id：{}退出小程序",SecurityUtils.getUser().getId());
		SysUser user = new SysUser();
		user.setUserId(SecurityUtils.getUser().getId());
		user.setLoginFlag(1);//退出，小程序需要重新绑定手机号
		sysUserService.updateById(user);
		return R.ok();
	}
	@ApiOperation(value = "b端小程序绑定头像昵称")
	@PostMapping("/bindHead")
	public R bindHead(@RequestBody SysUser user) {
		log.info("->用户id：{}绑定头像和昵称",SecurityUtils.getUser().getId());
		try {
			user.setUserId(SecurityUtils.getUser().getId());
			sysUserService.updateById(user);
			return R.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("更新头像失败");
		}
	}
	@ApiOperation(value = "获取用户绑定的商家")
	@PostMapping("/getBindSjList")
	public R<BindSjVo> bindSjList() {
		log.info("->获取用户绑定的商家");
		try {
			Integer userId = SecurityUtils.getUser().getId();
			UserExtDto userExt = new UserExtDto();
			userExt.setUserId(userId);
			userExt.setUserType(SecurityUtils.getUser().getUserType());
			userExt.setStatus(0);//上架
			return sysUserService.bindSjList(userExt);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}



}
